package cn.micai.base.task;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/7/16 10:55
 * @Description: 列举素数，直到它被取消 使用volatile域保存取消状态
 */
public class PrimeGenerator implements Runnable {

    private final List<BigInteger> primes = new ArrayList<>();

    private volatile boolean cancelled;

    @Override
    public void run() {
        BigInteger p = BigInteger.ONE;
        // PrimeGenerator每次搜索素数前检查是否有取消请求，当发现取消请求时就退出
        while (!cancelled) {
            p = p.nextProbablePrime();
            synchronized (this) {
                primes.add(p);
            }
        }
    }

    // 简单的取消策略
    public void cancel() {
        cancelled = true;
    }

    public synchronized List<BigInteger> get() {
        return new ArrayList<>(primes);
    }
}
